package com.example.homework7;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SharedPreferencesActivity extends AppCompatActivity {
    private static final String TAG = "SharedPreferencesAty";

    private String FILE_NAME = "user_info";

    private EditText mEtAccount;
    private EditText mEtPassword;
    private Button mBtnLogin;

    private String account;
    private String password;
    private String encrypted_password;//加密的密码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preferences);
        initView();
        initEvent();
    }

    private void initView() {
        mEtAccount = findViewById(R.id.et_account);
        mEtPassword = findViewById(R.id.et_password);
        mBtnLogin = findViewById(R.id.btn_login);
    }

    private void initEvent() {
        //首次启动页面就读取以前存取好的账号和密码（加密后的）
        setInitDataOfStorage();
        //登录按钮的点击事件
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: 登录");
                //获取输入框的数据（账号、密码）
                getAllData();
                //对密码进行加密
                setEncryptionPassword(password);
                //将账号和加密后的密码存储起来
                saveData();
            }
        });
    }

    /**
     * 将存储的账号、密码（加密后）设置到界面的输入框里
     */
    private void setInitDataOfStorage() {
        //使用SharedPreferences读取
        SharedPreferences preferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        String read_account = preferences.getString(Config.USER_ACCOUNT, "");
        String read_encrypted_password = preferences.getString(Config.USER_PASSWORD, "");
        Log.d(TAG, "initEvent: read_account = " + read_account);
        Log.d(TAG, "initEvent: read_encrypted_password = " + read_encrypted_password);
        //将读取好的数据设置到输入框中
        mEtAccount.setText(read_account);
        mEtPassword.setText(read_encrypted_password);
    }

    /**
     * 对密码进行sha256哈希加密
     */
    private void setEncryptionPassword(String password) {
        Log.d(TAG, "setEncryptionPassword: password = " + password );
        MessageDigest messageDigest;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(password.getBytes("UTF-8"));
            encrypted_password = byte2Hex(messageDigest.digest());
            Log.d(TAG, "setEncryptionPassword: encrypted_password = " + encrypted_password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     　　  * 将byte转为16进制
     　　  * @param bytes
     　　  * @return
     　　  */
    private static String byte2Hex(byte[] bytes){
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i=0;i<bytes.length;i++){
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length()==1){
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }


    /**
     * 用SharedPreferences保存账号和密码（已加密）
     */
    private void saveData() {
        SharedPreferences preferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(Config.USER_ACCOUNT, account);
        editor.putString(Config.USER_PASSWORD, encrypted_password);
        editor.commit();
        Toast.makeText(SharedPreferencesActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "saveData: account = " + account + ", encrypted_password = " + encrypted_password);
    }

    /**
     * 获取所有输入框的数据（账号、密码）
     */
    private void getAllData() {
        //获取明文账号和密码
        account = mEtAccount.getText().toString();
        password = mEtPassword.getText().toString();
    }
}
